"""
订单问题诊断脚本
"""
import requests
import json
from datetime import datetime

def test_order_api():
    """测试订单API"""
    print("🧪 测试订单API...")
    
    try:
        # 1. 测试创建订单
        order_data = {
            "goods_ids": [1],
            "quantities": [1],
            "remark": "诊断测试订单"
        }
        
        response = requests.post(
            "http://127.0.0.1:8000/api/orders/create",
            json=order_data,
            timeout=5
        )
        
        print(f"创建订单 - 状态码: {response.status_code}")
        if response.status_code == 200:
            result = response.json()
            print(f"✅ 订单创建成功: {result}")
            order_no = result.get("data", {}).get("order_no")
            
            # 2. 测试订单列表
            print("\n📋 测试订单列表...")
            list_response = requests.get("http://127.0.0.1:8000/api/orders/")
            print(f"订单列表 - 状态码: {list_response.status_code}")
            if list_response.status_code == 200:
                orders = list_response.json()
                print(f"订单数量: {len(orders) if isinstance(orders, list) else 'N/A'}")
                if isinstance(orders, list) and len(orders) > 0:
                    print("✅ 订单列表有数据")
                    for order in orders[:3]:  # 显示前3个订单
                        print(f"  - {order.get('order_no', 'N/A')}: {order.get('status', 'N/A')}")
                else:
                    print("⚠️  订单列表为空")
            
            return order_no
        else:
            print(f"❌ 订单创建失败: {response.text}")
            
    except Exception as e:
        print(f"❌ API测试失败: {e}")
    
    return None

def check_database_connection():
    """检查数据库连接"""
    print("🗄️  检查数据库连接...")
    
    try:
        from database.base import SessionLocal
        from models.order_models import Order
        
        db = SessionLocal()
        count = db.query(Order).count()
        db.close()
        
        print(f"✅ 数据库连接正常，订单表中有 {count} 条记录")
        return True
        
    except Exception as e:
        print(f"❌ 数据库连接失败: {e}")
        return False

def main():
    """主诊断流程"""
    print("🔍 订单问题诊断")
    print("=" * 60)
    
    # 1. 检查数据库
    db_ok = check_database_connection()
    
    print("\n" + "=" * 60)
    
    # 2. 测试API
    order_no = test_order_api()
    
    print("\n" + "=" * 60)
    print("📋 诊断结果:")
    
    if not db_ok:
        print("❌ 数据库连接有问题")
        print("💡 解决方案:")
        print("   1. 检查数据库服务是否启动")
        print("   2. 检查数据库连接配置")
        print("   3. 运行数据库初始化脚本")
    
    if order_no:
        print("✅ 订单创建API正常工作")
        print("⚠️  但订单可能没有保存到数据库")
        print("💡 这通常是因为:")
        print("   1. RabbitMQ消费者没有运行")
        print("   2. RabbitMQ服务连接失败")
        print("   3. 消费者处理消息时出错")
        
        print("\n🛠️  解决步骤:")
        print("   1. 启动RabbitMQ消费者:")
        print("      python order_consumer.py")
        print("   2. 或者运行临时处理脚本:")
        print("      python process_pending_orders.py")
        print("   3. 检查RabbitMQ队列状态:")
        print("      python check_rabbitmq_queue.py")
    else:
        print("❌ 订单创建API有问题")
        print("💡 请检查后端服务是否正常启动")

if __name__ == "__main__":
    main()
